<?php 
class Model{
	private static $link=NULL;
	private $table;
	private $opt;
	public function __construct($table){
		if (is_null(self::$link)) {
			$link=new Mysqli(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD'),C('DB_NAME'));
			if ($link->connect_errno) die($link->connect_error);
			$sql="SET NAMES " . C('DB_CHARSET');
			$link->query($sql);
			self::$link=$link;
			$this->error($sql);
		}
		$this->table=$table;
		$this->opt();
	}
	public function error($sql){
		if(self::$link->errno){
			halt("sql错误：" . self::$link->error . '<br/>' . "<h2 style='color:red'>有问题的sql：  {$sql}</h2>");
		}
	}
	public function opt(){
		$this->opt=array(
			'where'=>'',
			'field'=>'*',
			'group'=>'',
			'having'=>'',
			'order'=>'',
			'limit'=>''
		);
	}
	public function field($field){
		$this->opt['field']=$field;
		return $this;
	}
	public function where($where){
		$this->opt['where']=" WHERE {$where}";
		return $this;
	}
	public function group($group){
		$this->opt['group']=" GROUP BY {$group}";
		return $this;
	}
	public function having($having){
		$this->opt['having']=" HAVING {$having}";
		return $this;
	}
	public function order($order){
		$this->opt['order']=" ORDER BY {$order}";
		return $this;
	}
	public function limit($limit){
		$this->opt['limit']=" LIMIT {$limit}";
		return $this;
	}
	public function all(){
		$sql="SELECT ".$this->opt['field']."FROM ".$this->table.$this->opt['where'].$this->opt['group'].$this->opt['having'].$this->opt['order'].$this->opt['limit'];
		return $this->query($sql);
	}
	public function find(){
		$data=$this->all();
		return current($data);
	}
	public function query($sql){
		$result=self::$link->query($sql);
		$this->error($sql);
		$rows=array();
		while ($row=$result->fetch_assoc()) {
			$rows[]=$row;
		}
		$result->free();
		return $rows;
	}
	public function exec($sql){
		self::$link->query($sql);
		$this->error($sql);
	}
	public function add($data=NULL){
		if(is_null($data)) $data=$_POST;
		$fields= implode(',', array_keys($data));
		$values='"'.implode('","',array_values($data)).'"';
		$sql="INSERT INTO ".$this->table."({$fields}) VALUES ({$values})";
		$this->exec($sql);
	}
	public function update($data=NULL){
		if (!$this->opt['where']) {
			header('Content-type:text/html;charset=utf-8');
			die("请必须传递where条件才可以修改");
		}
		if(is_null($ata)) $data=$_POST;
		$info='';
		foreach ($data as $fields => $value) {
			$info.=$fields.'="'.$values.'",';
		}
		$info=rtrim($info,',');
		$sql="UPDATE ".$this->table."SET {$info}".$this->opt['where'];
		$this->exec($sql);
	}
	public function delete(){
		if (!$this->opt['where']) {
			header('Content-type:text/html;charset=utf-8');
			echo "请必须传递where条件才可以修改";
		}
		$sql="DELETE FROM ".$this->table.$this->opt['where'];
		$this->exec($sql);
	}






















}















































 ?>